//
//  LKHomeTableController.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 16/9/22.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
import SVProgressHUD
class LKHomeTableController: LKBaseTableViewController {
    //定义viewModel属性
    lazy var homeViewModel : LKHomeViewModel = LKHomeViewModel()
    //定义上拉刷新小菊花
    lazy var indicatorView: UIActivityIndicatorView = {
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        return indicatorView
    }()
    //定义下拉刷新界面
    lazy var pullToRefresh : LKRefreshControll = {
        let refresh = LKRefreshControll()
        refresh .addTarget(self, action: #selector(loadData), for: .valueChanged)
        return refresh
    } ()
    
    //定义刷新数据提示标签
    lazy var tipLable : UILabel = {
        let lable = UILabel(title: "", font: 14, textColor: UIColor.white)
        //设置背景颜色
        lable.backgroundColor = UIColor.orange
        //设置对齐
        lable.textAlignment = .center
        lable.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        lable.isHidden = true
        return lable
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", action: #selector(pushVC), target: self, title: "")
        
        vistorView.updateVistorViewInfo(tipTitle: "关注一些人,快回到这里看看有什么惊喜,", imageName: nil)
        setTableView()
        loadData()
    }
    func loadData() {
        homeViewModel.requestData(isPullingUp: indicatorView.isAnimating) { (success,count) in
            if !success{
                SVProgressHUD.showError(withStatus: "请求用户数据失败")
                return
            }
            //更改状态
            self.pullToRefresh.refreshStatus = .Default
            //走到这里说明成功了.刷新tableView
            self.tableView.reloadData()
            //停止下拉刷新动画
            self.pullToRefresh.stopAnimating()
            //数据加载完成停止动画
            self.indicatorView.stopAnimating()
            //显示提示lable动画
            self.startTipLableAnimation(count: count)
        }
    }
    //MARK:设置tableView
    private func setTableView () {
        //注册xib
        let originalNib = UINib(nibName: "LKStatusCell", bundle: nil)
        tableView?.register(originalNib, forCellReuseIdentifier: LKStatusCellID)
        let retweetedNib = UINib(nibName: "LKRetweetedCell", bundle: nil)
        tableView?.register(retweetedNib, forCellReuseIdentifier: LKRetweetedCellID)
        //设置属性
        tableView?.separatorStyle = .none
        tableView?.rowHeight = 360
        //将底部视图设为小菊花
        tableView?.tableFooterView = indicatorView
        //添加下拉刷新视图
        
        
        self.view.addSubview(pullToRefresh)
//        pullToRefresh.addTarget(self, action: #selector(loadData), for: .valueChanged)
        //添加提示标签
        //        self.view.addSubview(tipLable)
        //要添加到导航控制器上
        self.tipLable.frame.origin.y = navigationBarHeight - 35
        self.navigationController?.view.addSubview(tipLable)
        //一定要更改子控制器的顺序,否则tipLable显示在上方会像凭空冒出来一样
        self.navigationController?.view.insertSubview(tipLable, belowSubview: self.navigationController!.navigationBar)
    }
    func pushVC  ( )
    {
        self.navigationController?.pushViewController(LKTempViewController( ), animated: true)
    }
    private func startTipLableAnimation (count:Int) {
        //如果正在做动画就直接return
        if self.tipLable.isHidden == false {
            return
        }
        //设置label 的标题
        self.tipLable.text = count == 0 ? "没有新微博可显示" : "有\(count)条新微博"
        //动画前先显示label
        self.tipLable.isHidden = false
        UIView.animate(withDuration: 1, animations: {
            self.tipLable.frame.origin.y = navigationBarHeight
        }) { (_) in
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLable.frame.origin.y = navigationBarHeight - 35
                }, completion: { (_) in
                    self.tipLable.isHidden = true
            })
        }
    }
}
//MARK:tableView数据源分类
extension LKHomeTableController
{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.viewModelArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let viewModel = homeViewModel.viewModelArray[indexPath.row]
        let cellID = getCellID(viewModel: viewModel)
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! LKStatusCell
        //        let cell = tableView.dequeueReusableCell(withIdentifier: LKStatusCellID, for: indexPath) as! LKStatusCell
        cell.viewModel = viewModel
        return cell
    }
    //获取正确的cellID
    internal func getCellID (viewModel :LKStatusViewModel) -> String{
        return viewModel.status?.retweeted_status == nil ? LKStatusCellID : LKRetweetedCellID
    }
    
}
//MARK:tableView代理相关方法分类
extension LKHomeTableController {
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //创建一个不显示的cell
        let viewModel = homeViewModel.viewModelArray[indexPath.row]
        //获取重用标识符
        let cellID = getCellID(viewModel: viewModel)
        //获取cell
        //        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath),这样做会造成递归调用
        //直接从xib中加载
        let cell = getCell(reuseID: cellID)
        return cell.getRowHeight(viewModel: viewModel)
    }
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //静默加载,所以在倒数第2行cell显示的时候就转动小菊花,同时加载数据
        if indexPath.item == homeViewModel.viewModelArray.count - 2 {
            indicatorView.startAnimating()
            //加载数据
            loadData()
        }
    }
    //从xib中根据重用标识符获取cell
    private func getCell (reuseID: String) -> LKStatusCell {
        let nibName = reuseID == LKStatusCellID ? "LKStatusCell" : "LKRetweetedCell"
        let nib = UINib(nibName: nibName, bundle: nil)
        return nib.instantiate(withOwner: nil, options: nil).last as! LKStatusCell
    }
}
